<?php

class deliParser {

    var $items = array();
    var $item_tags = array('title', 'link', 'creator', 'date', 'subject', 'description');

    var $_source_encoding = 'UTF-8';
    var $_parser;
    
    var $_item;
    var $_tag;

    function deliParser($output_encoding=null) {
        
        $this->_parser = xml_parser_create($this->_source_encoding);

        if (!is_null($output_encoding))
            xml_parser_set_option($this->_parser, XML_OPTION_TARGET_ENCODING, $output_encoding);
        xml_set_object($this->_parser, $this);
        xml_set_element_handler($this->_parser, 'tag_open', 'tag_close');
        xml_set_character_data_handler($this->_parser, 'cdata');
    }

    function tag_open($parser, $tag, $attributes) {
        if (is_array($this->_item)) {
            $tag_tok = explode(':', $tag);
            if (count($tag_tok) == 2)
                $tag = $tag_tok[1];
            $tag = strtolower($tag);
            if (in_array($tag, $this->item_tags))
                $this->_tag = strtolower($tag);
        } else if ($tag == 'ITEM') {
            $this->_item = array();
        }
    }

    function tag_close($parser, $tag) {
        if ($tag == 'ITEM') {
            if (!isset($this->_item['description']))
                $this->_item['description'] = '';
            $this->items[] = $this->_item;
            $this->_item = null;
        }
    }

    function cdata($parser, $cdata) {
        if (is_null($this->_tag))
            return;
        $tag = $this->_tag;
        if ($tag == 'date') {
            list($d, $t) = explode('T', substr($cdata, 0, -1));
            list($y, $m, $d) = explode('-', $d);
            list($hh, $mm, $ss) = explode(':', $t);
            $cdata = mktime((int)$hh, (int)$mm, (int)$ss, (int)$m, (int)$d, (int)$y);
        }
        $this->_item["$tag"] = htmlentities($cdata, ENT_QUOTES);
        $this->_tag = null;
    }

    function parse($data, $free_parser=true) {
        $res = xml_parse($this->_parser, $data, true);
        if ($free_parser)
            $this->freeParser();
    }

    function freeParser() {
        xml_parser_free($this->_parser);
    }
    
}

require_once 'classes/LightPressPlugin.php';

class Delicious extends LightPressPlugin {
    
    var $constructor_args = array(
        'title'=>'title to show',
        'deliurl'=>'delicious RSS URL',
        'fetch_method'=>'\'native\' or \'curl\'',
        'timeout'=>'timeout when contacting delicious',
        'cache_time'=>'seconds to cache parsed entries',
        'limit_to'=>'how many entries to display');
    var $default_context = LP_CONTEXT_INDEX;
    var $description = 'Retrieve (cache) and show delicious bookmarks';
    
    
    var $active = true;
    var $hooks = array('sidebar');
    
    var $title = 'del.icio.us/ludoo';
    var $deliurl = 'http://del.icio.us/rss/ludoo/blog_en';
    var $fetch_method = 'native'; // native or curl
    var $timeout = 30;
    var $cache_time = 7200;
    var $limit_to = 6;
    
    var $_user_agent = 'LightPress/1.1 +http://lightpress.org/';
    
    function Delicious(&$frontend, $args, $dummy_run=false) {
        $this->LightPressPlugin($frontend, $args, $dummy_run);
        
        $this->timeout = (int)$this->timeout;
        $this->cache_time = (int)$this->cache_time;
        $this->limit_to = (int)$this->limit_to;
    }
    
    function run($hook, &$hook_data) {
        $db =& $this->_frontend->db;
        $tpl =& $this->_frontend->tpl;
        $table = $this->_frontend->tables['options'];
        $opt_exists = false; // WP uses auto-increment ints as primary keys for the opt table, ugh!
        $items = null;
        
        $db->query("select option_value from $table where option_name='lp_plugin_delicious'");
        if ($db->count == 1) {
            $opt_exists = true;
            $deli = unserialize(stripslashes($db->get('option_value')));
            if (($deli['parsed'] + $this->cache_time) >= mktime())
                $items = $deli['items'];
        }
        
        if (is_null($items)) {
            $content = $this->_getDelicious();
            if (!$content)
                return $this->hide();
            $output_encoding = $this->_frontend->options['charset'];
            $p =& new deliParser($output_encoding);
            $p->parse($content);
            $opt_value = array('parsed' => mktime());
            $opt_value['items'] =& $p->items;
            if ($opt_exists)
                $db->query("update $table set option_value='" . addslashes(serialize($opt_value)) . "' where option_name='lp_plugin_delicious'");
            else
                $db->query("insert into $table (option_name, option_value) VALUES ('lp_plugin_delicious', '" . addslashes(serialize($opt_value)) . "')");
            $items =& $p->items;
        }
        
        // limit items
        if (count($items) > $this->limit_to)
            $items = array_slice($items, 0, $this->limit_to);

        // add formatted fields
        $date_format = $this->_frontend->options['short_date_format'];
        // better here than in the db, as the stored items may be used for other purposes
        foreach ($items as $k=>$v) {
            $items[$k]['safe_description'] = htmlspecialchars($v['description'], ENT_QUOTES);
            $items[$k]['formatted_date'] = strftime($date_format, $v['date']);
        }
        
        $tpl->setFile('plugin_delicious', 'plugins/delicious.xml');
        $tpl->setVar(array(
            'plugin_delicious_title'   => $this->title,
            'plugin_delicious_url'     => $this->deliurl
            ));
        $tpl->parseBlock('PLUGIN_DELICIOUS_LINK', 'plugin_delicious_link', $items, 'plugin_delicious');
        $tpl->parse('PLUGIN_DELICIOUS', 'plugin_delicious');
    }
    
    
    function _getDelicious() {
        
        $fetch_method = $this->fetch_method;
        
        if ($fetch_method == 'native' && ini_get('allow_url_fopen') == 1) {
            // use the native PHP file functions
            ini_set('user_agent', $this->_user_agent);
            ini_set('default_socket_timeout', $this->timeout);
            $content = @file($this->deliurl);
            if (!is_array($content))
                return $content;
            return implode('', $content);
        } 
        
        if ($fetch_method == 'curl' && extension_loaded('curl')) {
            $c = curl_init($this->deliurl);
            // cURL options
            curl_setopt($c, CURLOPT_RETURNTRANSFER,1);
            curl_setopt($c, CURLOPT_CONNECTTIMEOUT, $this->timeout / 2);
            curl_setopt($c, CURLOPT_TIMEOUT, $this->timeout);
            curl_setopt($c, CURLOPT_USERAGENT, $this->_user_agent);
            $response = curl_exec($c);
            $info = curl_getinfo($c);
            $_curl_error_code = $info['http_code'];

            if($_curl_error_code == 200)
                return $response;
        }
        
        $ret = false;
        return $ret;
    }
    
}

//$content = file('delicious.xml');



?>
